const LOGIN_URL = 'https://taosha.club/api/v1/login';
const SHARE_URL = 'https://taosha.club/api/v1/topics/share';

// 切换登录界面和分享界面
var toggleForm = function () {
  $('.share-container').toggle();
  $('.login-container').toggle();
};

const KEY_ENTER = '13';
let share_content = null;


chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
  let currentTab = tabs[0]; // there will be only one in this array
  if (currentTab.title && currentTab.url) {
    document.querySelector('#title').value = currentTab.title;
    share_content = currentTab.url;
  }
});


$(function () {
  if (localStorage.blogAccessToken) {
    $('.share-container').show();
    $('.login-container').hide();
    $('#users').focus();
  } else {
    $('.login-container').show();
    $('.share-container').hide();
    $('#username').focus();
  }


  $('#login-btn').on('click', function () {
    let username = $('#username').val();
    let password = $('#password').val();

    $.post(LOGIN_URL, {username: username, password: password}, function (result) {
      if (result.success) {
        toggleForm();
        localStorage.setItem('blogAccessToken', result.data);
      } else {
        confirm(result.msg);
      }
    });
  });


  $('#share-btn').on('click', function () {
    const blogAccessToken = localStorage.getItem('blogAccessToken');

    let title = document.querySelector('#title').value;
    let content = share_content;
    let users = document.querySelector('#users').value;

    if (users) {
      content = content + '\n' + users;
    }

    let data = {
      title: title,
      content: content,
      tab: 'share',
      original_url: share_content,
      accesstoken: localStorage.getItem('blogAccessToken')
    }

    $.post(SHARE_URL, data, function (result) {
      confirm('分享成功!');
      window.close();
    }).error(function (error_result) {
      if (error_result.responseText) {
        confirm('已有相同标题的文章存在。');
      } else {
        confirm('系统异常。');
      }

    });
  });


  $('#logout-btn').on('click', function () {
    toggleForm();
    localStorage.removeItem('blogAccessToken');
  });

  $('body').bind('keyup', function (evt) {
    if (evt.keyCode == KEY_ENTER) {
      if (localStorage.getItem('blogAccessToken')) {
        $('#share-btn').click();
      } else {
        $('#login-btn').click();
      }
    }
  });

});
